package com.zhouxiaoge.jenkins.config;

import com.offbytwo.jenkins.JenkinsServer;
import com.offbytwo.jenkins.client.JenkinsHttpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author 周明阳
 * @date 2019/7/17 18:14
 * Jenkins连接配置
 */

@Configuration
@Slf4j
public class JenkinsConfig {
    /**
     * 为jenkinsProperties注入配置值，也可以在jenkinsProperties上添加Component注解和ConfigurationProperties(prefix="project.jenkins")注解来实现注入功能
     */
    @Bean(name = "jenkinsProperties")
    public JenkinsProperties jenkinsProperties(
            @Value("${jenkins.serverUrl}") String serverUrl,
            @Value("${jenkins.userName}") String userName,
            @Value("${jenkins.passWord}") String passWord) {
        JenkinsProperties jenkinsProperties = new JenkinsProperties();
        jenkinsProperties.setServerUri(serverUrl);
        jenkinsProperties.setUserName(userName);
        jenkinsProperties.setPassWord(passWord);
        log.info("serverUrl->{},userName->{},passWord->{}", serverUrl, userName, passWord);
        return jenkinsProperties;
    }


    @Bean(name = "jenkinsHttpClient")
    @Scope(scopeName = ConfigurableBeanFactory.SCOPE_SINGLETON)
    public JenkinsHttpClient getJenkinsHttpClient(@Qualifier("jenkinsProperties") JenkinsProperties jenkinsProperties) throws URISyntaxException {
        return new JenkinsHttpClient(new URI(jenkinsProperties.getServerUri()), jenkinsProperties.getUserName(), jenkinsProperties.getPassWord());
    }

    /**
     * 注入jenkinsServer对象
     */
    @Bean(name = "jenkinsServer")
    @Scope(scopeName = ConfigurableBeanFactory.SCOPE_SINGLETON)
    public JenkinsServer getJenkinsServer(@Qualifier("jenkinsHttpClient") JenkinsHttpClient jenkinsHttpClient) {
        JenkinsServer jenkinsServer = new JenkinsServer(jenkinsHttpClient);
        boolean running = jenkinsServer.isRunning();
        //判断是否成功连接Jenkins,后期完善
        System.out.println("Jenkins is running ====> " + running + "！！！");
        return new JenkinsServer(jenkinsHttpClient);
    }

}
